package com.zbcz.erp.viewmodel

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.zbcz.erp.bean.BusinessAddBean
import com.zbcz.erp.bean.BusinessApplyBean
import com.zbcz.erp.bean.DictItem
import com.zbcz.erp.network.ErpApi
import com.zbcz.erp.network.RetrofitManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File

/**
 * 用例申请
 */
class CommonRequestViewModel : BaseViewModel() {

    companion object {
        const val TAG = "ApplyForSealViewModel"
        const val DOCUMENT_TYPE = "document_type" //文件类别
        const val SEAL_TYPE = "seal_type"         //印章类别
        const val CONTRACT_PAYMENT_STATUS = "contract_payment_status"
        const val CONTRACT_TYPE = "contract_type"
        const val PAYMENT_PROPORTION = "payment_proportion"
        const val UNIT = "unit"
        const val IS_ON = "is_on"
        const val ACCESSORY_TYPE = "accessory_type"
        const val PRODUCT_TYPE = "product_type"
        const val PROJECT_STATUS = "project_status"
        const val PAYMENT_TYPE = "payment_type"
    }

    private val mApi = RetrofitManager.getRetrofit()?.create(ErpApi::class.java)

    var requestResult: MutableLiveData<Pair<String,Boolean?>> = MutableLiveData()
    var mSealTypeDicItemLiveData: MutableLiveData<List<DictItem>?> = MutableLiveData()
    var mDocTypeDicItemLiveData: MutableLiveData<List<DictItem>?> = MutableLiveData()
    var mPaymentTypeLiveData: MutableLiveData<List<DictItem>?> = MutableLiveData()

    //applyBean: BusinessApplyBean
    fun createRequest(addBean: BusinessAddBean, file: File?) {
        viewModelScope.launch {
            withContext(Dispatchers.IO) {
                if (file != null) {
                    val uploadImageResult = uploadImageSuspend(file)
                    Log.i(TAG, "uploadFileName=" + uploadImageResult.toString())
                    addBean.file = uploadImageResult
                    addBean.business_file = uploadImageResult ?: ""
                    addBean.report_business_file = uploadImageResult ?: ""
                    addBean.travel_business_file = uploadImageResult ?: ""
                }
                val result = businessAdd(addBean)
                Log.i(TAG, result.toString())
                if (result != null) {
                    val businessApplyBean = BusinessApplyBean().apply {
//                        tableId = result
                        firstGateway = true
                        id = result
                        procDefId = addBean.procDefId ?: ""
                        title = addBean.procDeTitle ?: ""
                    }
                    val applyResult = businessApply(businessApplyBean)
                    requestResult.postValue(applyResult)
                    Log.i(TAG, applyResult.toString())
                }
            }
        }
    }

    fun createEditRequest(addBean: BusinessAddBean, file: File?, mId: String?) {
        viewModelScope.launch {
            withContext(Dispatchers.IO) {
                if (file != null) {
                    val uploadImageResult = uploadImageSuspend(file)
                    Log.i(TAG, "uploadFileName=" + uploadImageResult.toString())
                    addBean.file = uploadImageResult
                }
                val result = editFormSuspend(addBean)
                Log.i(TAG, result.toString())
                if (result == true) {
                    val businessApplyBean = BusinessApplyBean().apply {
                        firstGateway = true
                        id = mId ?: ""
                        procDefId = addBean.procDefId ?: ""
                        title = addBean.procDeTitle ?: ""
                    }
                    val applyResult = businessApply(businessApplyBean)
                    requestResult.postValue(applyResult)
                    Log.i(TAG, applyResult.toString())
                }
            }
        }
    }

    private suspend fun queryFormInfoSuspend(
        tableId: String,
        tableName: String,
    ): BusinessAddBean? {
        try {
            val result = mApi?.actBusinessGetForm(tableId = tableId, tableName = tableName)
            if (result?.code == 200) {
                return result.result
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }


    var mQueryFormInfo: MutableLiveData<BusinessAddBean?> = MutableLiveData()
    var mActPassLiveData: MutableLiveData<Pair<Boolean, String?>> = MutableLiveData()
    var mActBackLiveData: MutableLiveData<Pair<Boolean, String?>> = MutableLiveData()
    var mEditFormLiveData: MutableLiveData<Boolean> = MutableLiveData()

    fun queryFormInfo(
        tableId: String,
        tableName: String
    ) {
        viewModelScope.launch {
            withContext(Dispatchers.IO) {
                val result = queryFormInfoSuspend(tableId, tableName)
                mQueryFormInfo.postValue(result)
            }
        }
    }

    fun actPass(
        isPass: Boolean,
        id: String,
        procInstId: String,
        comment: String?
    ) {
        viewModelScope.launch {
            withContext(Dispatchers.IO) {
                if (isPass) {
                    mActPassLiveData.postValue(
                        actPassSuspend(
                            id,
                            procInstId,
                            comment
                        )
                    )
                } else {
                    mActBackLiveData.postValue(
                        actBackSuspend(
                            id,
                            procInstId,
                            comment
                        )
                    )
                }
            }
        }
    }


    private suspend fun actPassSuspend(
        id: String,
        procInstId: String,
        comment: String?
    ): Pair<Boolean, String?> {
        try {
            val result = mApi?.actTaskPass(id, procInstId, comment ?: "")
            return if (result?.code == 200 && result.success) {
                Pair(true, result.message)
            } else {
                Pair(false, result?.message)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return return Pair(false, "")
    }

    private suspend fun actBackSuspend(
        id: String,
        procInstId: String,
        comment: String?
    ): Pair<Boolean, String?> {
        try {
            val result = mApi?.actTaskBack(id, procInstId, comment ?: "")
            return if (result?.code == 200 && result.success) {
                Pair(true, result.message)
            } else {
                Pair(false, result?.message)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return return Pair(false, "")
    }


    private suspend fun editFormSuspend(addBean: BusinessAddBean): Boolean? {
        try {
            val result = mApi?.editGetForm(addBean)
            if (result?.code == 200) {
                return true
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return false
    }

    fun getDicItem(dictCode: String) {
        viewModelScope.launch {
            withContext(Dispatchers.IO) {
                val dicItem = getDicItems(dictCode)
//                var mMap = mDicItemLiveData.value
//                if (mMap == null) {
//                    mMap = HashMap()
//                }
//                mMap[dictCode] = dicItem
                when (dictCode) {
                    SEAL_TYPE -> mSealTypeDicItemLiveData.postValue(dicItem)
                    DOCUMENT_TYPE -> mDocTypeDicItemLiveData.postValue(dicItem)
                    PAYMENT_TYPE -> mPaymentTypeLiveData.postValue(dicItem)
                }
                Log.i(TAG, dicItem.toString())
            }
        }
    }


    private suspend fun getDicItems(dictCode: String): List<DictItem>? {
        try {
            val result = mApi?.getDictItems(dictCode)
            if (result != null) {
                return result
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }
}